package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class NUS_Android extends Activity {
	public static String IVLE_Token;
	final Context myApp = this;
	public static ProgressDialog pd;
	private JSONObject jObject;
	//protected TextView title;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_titlemain);
		 //title = (TextView) findViewById(R.id.titleheader);
		// title.setText("NDroidUS");
		WebView wv = (WebView) findViewById(R.id.wv);
	
		wv.getSettings().setJavaScriptEnabled(true);
		wv.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
		wv.setWebViewClient(new WebViewClient() {
			
			@Override
			public void onPageFinished(WebView view, String url) {
				
				// Log.d("url: " + url, "onPageFinished");
				// when login is complete, the url will be login_result.ashx?r=0
				if (url.indexOf("/api/login/login_result.ashx") > 0) {
					// When login is successful, there will be a &r=0 in the
					// url. It also means the return data is the token itself.
					if (url.indexOf("&r=0") > 0) {
						// Log.d("success", "onPageFinished");
						// Log.i("onPageFinished - before loading javascript",
						// "");
						view.setBackgroundColor(Color.BLACK);
						view.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('body')[0].innerHTML);");
					}
				}
			}
		});
		wv.loadUrl("https://ivle.nus.edu.sg/api/login/?apikey=W7RtgW7GZKUpaEkJ1NwUD&url=");
		// wv.loadUrl("https://aces01.nus.edu.sg/SrcvcbWeb/jsp/general/logon.jsp");
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
			startActivity(new Intent("com.nus.IvleNewsActivity"));
		}
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (((WebView) findViewById(R.id.wv)).canGoBack()) {
				((WebView) findViewById(R.id.wv)).goBack();
			} else {
			finish();
			}
			return true;
			}
        return false;
	}

	class MyJavaScriptInterface {
		@SuppressWarnings("unused")
		public void processHTML(String html) {
			IVLE_Token = html;

			// process the html as needed by the app

			// new AlertDialog.Builder(myApp)
			// .setTitle("Token Value")
			// .setMessage(IVLE_Token)
			// .setPositiveButton(android.R.string.ok, null)
			// .setCancelable(false)
			// .create();
			// .show(); //prompt display for token for checking

			// print out the token or save for next logon or to navigate to next
			// API call.
			Log.i("Token", IVLE_Token);
			String url = "https://ivle.nus.edu.sg/api/Lapi.svc/PublicNews?APIKey=W7RtgW7GZKUpaEkJ1NwUD&TitleOnly=false";
            startLoading("Logging in");
			// startActivity(new Intent("com.nus.IvleNewsActivity"));
			startActivity(new Intent("com.nus.OptionsActivity"));
			// callMyURL(IVLE_Token);
		}

	}
	public void startLoading(String msg) {
		
		pd = ProgressDialog.show(NUS_Android.this, msg,
				"Please wait ...", true);
		pd.setIcon(R.drawable.header);

		// return super.onKeyDown(keyCode, event);
	}

	

	public static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			pd.dismiss();

		}
	};
}